package com.netty.websocket.netty;

import com.alibaba.fastjson.JSON;
import com.netty.websocket.common.enums.CommonConstant;
import com.netty.websocket.common.enums.PushTypeEnums;
import com.netty.websocket.common.enums.WsSubTypeEnum;
import com.netty.websocket.common.javabean.WsRespVo;
import com.netty.websocket.common.util.RedisUtil;
import com.netty.websocket.common.util.SpringUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * @ClassName: WebSocketHandler
 * @Description: TextWebSocketFrame类型， 表示一个文本帧
 * @author yuyehong@cloudwalk.cn
 * @date 2020年4月29日 上午1:22:16
 * @version v1.3.0
 * @since 1.8
 */
@Component
@Slf4j
public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    /**
     * 客户端与服务器建立连接时触发
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("与客户端建立连接，通道开启！channelActive 被调用" + ctx.channel().id().asLongText());
        // 添加到channelGroup 通道组
        NettyConfig.addChannel(ctx.channel());
    }

    /**
     * 客户端与服务器关闭连接时触发
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        String channelLongId = ctx.channel().id().asLongText();
        log.info("channelInactive 被调用" + channelLongId);
        // 删除通道
        NettyConfig.removeChannel(ctx.channel());

        AttributeKey<String> key = AttributeKey.valueOf("wsSubType");
        String wsSubType = ctx.channel().attr(key).get();
        WsSubTypeEnum type = WsSubTypeEnum.getByKey(Integer.parseInt(wsSubType));
        switch (type) {
            case ONE:
                hdelRedisCache("user", channelLongId);
                break;
            default:
                log.info("未知来源");
                break;
        }
    }

    /**
     * 服务器接收客户端的数据消息
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        log.info("服务器收到消息：{}", msg.text());
        String channelLongId = ctx.channel().id().asLongText();
        ReceiveDataContent receive = JSON.parseObject(msg.text(), ReceiveDataContent.class);
        // 用户ID
        String userId = receive.getUserId();
        if (StringUtils.isBlank(userId)) {
            log.info("用户ID为空，不记录连接信息");
            return;
        }
        Integer subType = receive.getSubType();
        // 订阅类型
        WsSubTypeEnum type = WsSubTypeEnum.getByKey(subType);
        switch (type) {
            case ONE:
                // 总首页存用户ID
                hSetRedisCache("user", channelLongId, userId);
                log.info("通道ID：{}", channelLongId);
                break;
            default:
                log.info("未知来源");
                break;
        }
        // 将socket订阅类型作为自定义属性加入到channel中，方便随时channel中获取
        //也可以将用户ID绑定到属性中去
        AttributeKey<String> key = AttributeKey.valueOf("wsSubType");
        ctx.channel().attr(key).setIfAbsent(String.valueOf(subType));
        // 回复消息
        ctx.channel().writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(buildWsResp("连接成功", PushTypeEnums.USER_IDENTIFICATION))));
    }

    /**
     * 删除redis缓存
     * @Title: hdelRedisCache
     * @author yuyehong@cloudwalk.cn
     * @date 2020年4月30日 上午10:42:09
     * @param key  key
     * @param item item
     */
    private void hdelRedisCache(String key, Object... item) {
        RedisUtil redisUtil = SpringUtil.getBean(RedisUtil.class);
        redisUtil.hdel(key, item);
    }

    /**
     * 缓存redis
     * @Title: hSetRedisCache
     * @author yuyehong@cloudwalk.cn
     * @date 2020年4月30日 上午10:43:38
     * @param key   key
     * @param item  item
     * @param value value
     */
    private void hSetRedisCache(String key, String item, Object value) {
        RedisUtil redisUtil = SpringUtil.getBean(RedisUtil.class);
        redisUtil.hset(key, item, value);
    }

    private WsRespVo buildWsResp(Object msg, PushTypeEnums type) {
        WsRespVo wsRespVo = WsRespVo.builder().id(UUID.randomUUID().toString())
                .date(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now())).typeCode(type.getKey()).type(type.getValue())
                .message(type.getRemark()).code(CommonConstant.CW_STATUS_CODE_SUCCESS).data(msg).build();
        return wsRespVo;
    }
}
